package org.mcjug.locationmailer.oauth.tokens;

import oauth.signpost.OAuthConsumer;
import oauth.signpost.OAuthProvider;

import org.mcjug.locationmailer.R;
import org.mcjug.locationmailer.util.Constants;
import org.mcjug.locationmailer.util.ExceptionUtil;
import org.mcjug.locationmailer.util.RunnableWithException;

import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import android.os.AsyncTask;
//import android.util.Log;

public class OAuthRequestTokenTask extends AsyncTask<Void, Void, Void> {
    private final String TAG = getClass().getSimpleName();
    private Context context;
    private OAuthProvider provider;
    private OAuthConsumer consumer;

    /**
     * 
     * We pass the OAuth consumer and provider.
     * 
     * @param context Required to be able to start the intent to launch the browser.
     * @param provider The OAuthProvider object
     * @param consumer The OAuthConsumer object
     */
    public OAuthRequestTokenTask(Context context, OAuthConsumer consumer, OAuthProvider provider) {
        //Log.d(TAG, "In OAuthRequestTokenTask");
        this.context = context;
        this.consumer = consumer;
        this.provider = provider;
    }

    /**
     * 
     * Retrieve the OAuth Request Token and present a browser to the user to authorize the token.
     * 
     */
    protected Void doInBackground(Void... params) {

        try {
            //Log.d(TAG, "Retrieving request token from Google servers");
            String oathCallbackScheme = Constants.getProperty(context, R.string.oauthCallbackSchemePreferenceName,
                    R.string.oauthCallbackSchemeDefaultValue);
            String oauthCallbackUrl = Constants.getProperty(context, R.string.oauthCallbackUrlPreferenceName,
                    R.string.oauthCallbackUrlDefaultValue);

            final String url = provider.retrieveRequestToken(consumer, oathCallbackScheme + "://" + oauthCallbackUrl);
            //Log.d(TAG, "Popping a browser with the authorize URL : " + url);
            Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse(url)).setFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP
                    | Intent.FLAG_ACTIVITY_NO_HISTORY | Intent.FLAG_FROM_BACKGROUND);
            context.startActivity(intent);
            //Log.d(TAG, "Context.startActivity(intent)");
        } catch (Exception e) {
            //Log.e(TAG, "OAuthRequestTokenTask doInBackground error", e);
            ExceptionUtil.exceptAway(context, e, "OAuthRequestTokenTask doInBackground error: ",
                    new RunnableWithException() {

                        @Override
                        public void run() throws Throwable {
                            cancel(true);
                        }
                    });
        }

        return null;
    }
}
